<template>
    <div class="addBrand-container">
      <el-page-header @back="goBack" :content="content" style="margin-bottom:20px">
      </el-page-header>
    <div class="container">
      <el-form ref="ruleForm"
               :model="ruleForm"
               :inline="false"
               label-width="180px"
               class="demo-ruleForm">

        <el-form-item label="商品类型">
          <el-select v-model="categoryId" @change="getProduct(categoryId)" placeholder="类型"  >
            <el-option :label="category.name" :value="category.id" v-for="(category,index) in categorys" :key="index"></el-option>
            <!-- <el-option label="区域二" value="beijing"></el-option> -->
          </el-select>
        </el-form-item>

        <el-form-item label="商品">
          <el-autocomplete
            class="inline-input"
            v-model="product"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>

        <el-form-item label="数量:"
                      prop="price"
                      class="idNumber">
          <el-input v-model.number="ruleForm.productNum"
                    placeholder="请输入商品数量">
                    <!-- <template slot="append">元</template> -->
          </el-input>
        </el-form-item>

        <el-form-item label="生产日期:"
                      prop="name">
                <div class="block">
                  <!-- <span class="demonstration">带快捷选项</span> -->
                  <el-date-picker
                    v-model="ruleForm.dateOfManufacture"
                    align="right"
                    type="datetime"
                    placeholder="选择日期时间"
                    format="yyyy 年 MM 月 dd 日 HH 时 mm分 ss秒"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="pickerOptions">
                  </el-date-picker>
                </div>
        </el-form-item>

        <el-form-item label="商店" v-if="this.$store.state.user.userInfo.storeId == 0">
          <el-select v-model="ruleForm.storeId" placeholder="商店"  >
            <el-option :label="store.name" :value="store.id" v-for="(store,index) in stores" :key="index"></el-option>
            <!-- <el-option label="区域二" value="beijing"></el-option> -->
          </el-select>
        </el-form-item>

        <div class="subBox address">
          <!-- <el-form-item> -->
          <el-button @click="() => $router.push('/home/inventory')">
            取消
          </el-button>
          <el-button type="primary"
                     :class="{ continue: actionType === 'add' }"
                     @click="submitForm(actionType)">
            保存
          </el-button>
          <!-- <el-button v-if="actionType == 'add'"
                     type="primary"
                     @click="submitForm('ruleForm', true)">
            保存并继续添加
          </el-button> -->
          <!-- </el-form-item> -->
        </div>
      </el-form>
    </div>
  </div>
</template>


<script>
import {queryProductById,updateProduct,addProduct,productPage} from '@/api/product'
import {addInventory,updateInventory,inventoryQueryById} from '@/api/inventory'
import {categoryPage,queryCategoryById} from '@/api/category'
import {storePage} from '@/api/store'
export default{

  data() {
    return {
      content:'添加库存',
      ruleForm:{
        dateOfManufacture: "",
        id: 0,
        productId: 0,
        productNum: 0,
        shelfLife: 0,
        storeId: this.$store.state.user.userInfo.storeId
      },
      rules:'',
      actionType:'',
      categorys:[],
      products:[],
      stores:[],
      product:null,
      restaurants: [],
      categoryId:'',
      user:null,
      pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        value1: '',
        value2: '',
    }
  },
  created(){
    this.actionType = this.$route.query.methods
    
    this.categoryId = this.$route.query.categoryId
    queryCategoryById(this.categoryId).then((res)=>{
      this.categoryId = res.data.name
    })
    this.getProduct(this.$route.query.categoryId)

    if(this.actionType == 'add'){
      this.content='添加库存'
    }else{
      this.content='修改库存信息'
      inventoryQueryById(parseInt(this.$route.query.id)).then((res)=>{
        console.log(res.data)
        // this.ruleForm =  Object.assign(res.data)
        this.product = this.$route.query.name
        // this.ruleForm.id = this.$route.query.id
        Object.keys(this.ruleForm).forEach(key => {
          this.ruleForm[key] = res.data[key] == undefined ? this.ruleForm[key] : res.data[key]
      })

      }).catch((err)=>{
        this.$message.error('inventoryQueryById:'+err)
      })
      
    }
    //查询所有分类
    const res2 = categoryPage('',1,10,'')
    res2.then((res)=>{
      // console.log(res.data)
      this.categorys = res.data.records
    }).catch((err)=>{
      this.$message.error(err)
    })

    

    //查询所有商店
    storePage(null,1,999).then((res)=>{
      this.stores = res.data.records
    }).catch((err)=>{
      this.$message.error(err)
    })
    
  },
  methods:{
    submitForm(value){
      console.log(this.ruleForm)
      let res;
      if(value == 'add'){
        res = addInventory(this.ruleForm)
        res.then((res)=>{
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.$router.push('/home/inventory')
        }).catch((err)=>{
          this.$message.error(err);
        })
      }
      else if(value == 'update'){
        console.log(value)
        console.log(this.ruleForm)
        res = updateInventory(this.ruleForm)
        res.then((res)=>{
          this.$message({
            message: '更新成功',
            type: 'success'
          });
          console.log(res)
          this.$router.push('/home/inventory')
        }).catch((err)=>{
          console.log(err)
          this.$message.error(err);
        })
      }
    },
    goBack(){
      this.$router.go(-1)
    },
    querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
    createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        }
      },
    handleSelect(item) {
      // console.log(this.restaurants)
        let product = this.products.find(p=>p.id == item.id)
        this.ruleForm.productId = product.id
        // console.log(product)
        this.ruleForm.shelfLife = product.expirationDate
        console.log(this.ruleForm)
        // this.product = item
      },
    getProduct(categoryId,status){
        this.products = []
        this.restaurants = []
        productPage(categoryId,null,1,9999,status).then((res)=>{
        this.products = res.data.records
        //forEach构造this.restaurants
        res.data.records.forEach((data)=>{
          let product = {
            value:data.name,
            id:data.id
          }
          this.restaurants.push(product)
        })

        console.log( this.restaurants)
      }).catch((err)=>{
        this.$message.error(err)
      })
      }

  },
  watch:{
    // categoryId(item1,item2){ // item1为新值，item2为旧值
    //   console.log(item1)
    //   this.getProduct(item1,1)
    // },
    immediate:false
  }
}
</script>

<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 30px;
    margin-top: 0px;
    .HeadLable {
      background-color: transparent;
      margin-bottom: 0px;
      padding-left: 0px;
    }
    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;

    }
    .idNumber {
      margin-bottom: 39px;
    }

    .el-form-item {
      margin-bottom: 29px;
    }
    .el-input {
      width: 293px;
    }
  }
}

.demo-ruleForm{
  width: 600px;
}

.uploadImage{
  border-radius: 5px;
}
</style>